import sys
from pathlib import Path
import json
from typing import Optional

sys.path.append(str(Path(__file__).parent.parent.parent))
from reqapi.api import BaseApi, ApiConfig
from model.sms_up_config_models import SmsUpConfigResponse


class AuthSmsUpConfigApi(BaseApi):
    """短信上行配置API"""
    
    def get_sms_up_sign_in_config(self, raise_on_error: bool = False) -> Optional[SmsUpConfigResponse]:
        """获取短信上行登录配置，统一风格，异常和错误码返回 None"""
        endpoint = "/api/user/Auth/GetSmsUpSignInConfig"
        url = f"{self.BASE_URL}{endpoint}"
        headers = self.common_headers.copy()
        headers["apptype"] = "7"
        headers["authorization"] = "Bearer"
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: GET")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, method="GET", headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                resp_json = response
            elif hasattr(response, 'json'):
                resp_json = response.json()
            else:
                resp_json = response
            print(f"响应内容: {json.dumps(resp_json, indent=2, ensure_ascii=False)}")
            code_val = resp_json.get('Code', resp_json.get('code', -1))
            if code_val != 0:
                print(f"API返回错误: {resp_json.get('Msg', resp_json.get('msg', '未知错误'))}")
                if raise_on_error:
                    raise Exception(f"业务处理失败: {resp_json.get('Msg', resp_json.get('msg'))}")
                return None
            if hasattr(SmsUpConfigResponse, 'from_dict'):
                return SmsUpConfigResponse.from_dict(resp_json)
            return SmsUpConfigResponse(**resp_json)
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            if raise_on_error:
                raise
            return None


def main():
    """测试获取短信上行配置API"""
    try:
        # 使用示例设备ID
        device_id = "Z+Y6b2IPUIgDAPCT+TR/1bNK"
        
        # 创建API实例
        api = AuthSmsUpConfigApi(
            device_token=device_id,
            device_id=device_id,
            auth_token="Bearer",  # 根据请求示例设置
            uk="5FGalKSuELr9iaAi6w13dX3GZq3J7fXtzyv3SloVrBx5pKxpaC82CMwdxSIZMo11L"  # 示例UK值
        )
        
        # 发送请求
        response = api.get_sms_up_sign_in_config()
        
        # 打印结果
        print("\n获取短信上行配置结果:")
        print(f"状态码: {response.Code}")
        print(f"消息: {response.Msg}")
        print(f"提示类型: {response.TipType}")
        
        # 检查是否成功
        if response.Code == 0 and response.Data:
            print(f"短信上行内容: {response.Data.SmsUpContent}")
            print(f"短信上行号码: {response.Data.SmsUpNumber}")
        else:
            print(f"获取失败，错误码: {response.Code}")
            print(f"错误信息: {response.Msg}")
        
    except Exception as e:
        print(f"获取短信上行配置失败: {e}")


if __name__ == "__main__":
    main()
